package com.swu.ws.homework;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class Downloader {
    public static void downloadFile(String url, String localFilePath) throws IOException {
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
        con.setRequestMethod("GET");
        int responseCode = con.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            InputStream in = new BufferedInputStream(con.getInputStream());
            FileOutputStream fos = new FileOutputStream(localFilePath);
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                fos.write(buffer, 0, bytesRead);
            }
            in.close();
            fos.close();
            System.out.println("文件下载成功!");
        } else {
            System.out.println("文件下载失败. Response code: " + responseCode);
        }
        con.disconnect();
    }
}
